package admin_server

import (
	"encoding/json"
	"github.com/zeast/logs"
	"lark/conf"
	"lark/dove"
	"sync"
	"time"
)

var gwl = &whiteList{
	ips:      conf.AdminWhitelist,
	updateAt: time.Now(),
}

type whiteList struct {
	sync.RWMutex
	ips      []string
	updateAt time.Time
}

func (wl *whiteList) allow(addr string) bool {
	wl.Lock()
	defer wl.Unlock()

	if time.Since(wl.updateAt) > time.Second*30 {
		wl.update()
		wl.updateAt = time.Now()
	}

	return wl.check(addr)
}

//检查 addr 是否在白名单中
func (wl *whiteList) check(addr string) bool {
	if addr == "127.0.0.1" {
		return true
	}

	for _, ip := range wl.ips {
		if ip == addr {
			return true
		}
	}

	return false
}

//更新白名单
func (wl *whiteList) update() {
	data, err := dove.Get(conf.DoveKeyOfAdminWhitelist)
	if err != nil {
		logs.Error(err)
		return
	}

	err = json.Unmarshal(data, &conf.AdminWhitelist)
	if err != nil {
		logs.Error(err)
		return
	}

	wl.ips = conf.AdminWhitelist
}
